package com.martin.lib_base.base

import android.content.Context
import android.content.Intent
import androidx.lifecycle.ViewModel
import com.martin.lib_base.interfaces.ILoading
import com.martin.lib_base.interfaces.IRelease
import com.martin.lib_base.ktx.finish
import com.martin.lib_base.model.LoadingModel
import com.martin.lib_base.utils.ReleaseUtil
import dev.DevUtils
import kotlin.properties.Delegates

/**
 * @desc：
 */
open class BaseViewModel : ViewModel(), ILoading, IRelease {

    //加载弹窗
    private var _loadingModel: LoadingModel? = null

    var context: Context by Delegates.notNull()

    /**
     * 初始化
     * 防止获取Activity不是当前Activity
     */
    open fun initContext(context: Context, intent: Intent = Intent()) {
        this.context = context
        _loadingModel = LoadingModel(context)
    }

    /**
     * 展示加载弹窗
     */
    override fun showLoading() {
        if (_loadingModel == null) {
            _loadingModel = LoadingModel(DevUtils.getTopActivity())
        }
        _loadingModel?.showLoading()
    }

    override fun dismissLoading() {
        _loadingModel?.dismissLoading()
    }

    override fun onCleared() {
        release()
    }

    override fun release() {
        dismissLoading()
        ReleaseUtil.release(this)
    }

    fun finish() {
        dismissLoading()
        context.finish()
    }
}